const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const setFilePath = require('./webpack.setFilePath')

const abPath = path.resolve(__dirname,'..')

const srcDir = abPath+"/src";

console.log(abPath)


//单入口函数
function getOneEntry(filename){

  let arrPath = {}

  arrPath[filename] = abPath+'/src/pages/'+filename+'/index.js';

  return arrPath;
}


//单模版文件输出
function getOneHtmlWebpackPlugin(file){
  let arrHtmlPlugin = [];
  arrHtmlPlugin.push(new HtmlWebpackPlugin({
    template:abPath+'/src/pages/'+file+'/index.ejs',
    filename:file+'.html',
    inject:'body',
    title:'webpack app',
    chunks:[file]
  }));

  return arrHtmlPlugin;
}

//多入口函数
function getAllEntry(){

    let arrPath = {};
    fs.readdirSync(abPath+'/src/pages').forEach(filename=>{
      let stat = fs.statSync(abPath+'/src/pages/'+filename)
      
      if(stat && stat.isDirectory()){
        arrPath[filename] = abPath+'/src/pages/'+filename+'/index.js';
      }
        
    })
    return arrPath;
}


//打包多个页面
function getAllHtmlWebpackPlugin(){
  let arrHtmlPlugin = [];
  fs.readdirSync(abPath+'/src/pages').forEach(file=>{


    let stat = fs.statSync(abPath+'/src/pages/'+file)
      
      if(stat && stat.isDirectory()){
        arrHtmlPlugin.push(new HtmlWebpackPlugin({
          template:abPath+'/src/pages/'+file+'/index.html',
          filename:file+'.html',
          inject:'body',
          title:'webpack app',
          chunks:[file]
        }));
      }

    
  })

  return arrHtmlPlugin;
}

module.exports = {
  context:abPath,
  entry:getOneEntry(setFilePath),
  plugins:getOneHtmlWebpackPlugin(setFilePath),
  module:{
    rules:[
      {
        test:/\.js$/,
        exclude:/node_modules/,
        include:/pages/,
        use:['babel-loader']
      }
    ]
  },
  output:{
      filename:'js/[name].bundle.js',
      path:abPath+'/dist',
      // publicPath:'http:www/'  //加在script引用js前面的字符串
  },
  resolve:{
    extensions:['.js'],
    modules:[srcDir,'node_modules'],
    alias:{
      "vd":srcDir+"/vendor",
      "co":srcDir+"/common/js",
      "@":"./components",
      "~":srcDir+'/'
    }
  }
}